//
//  HomeDetailViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/1.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "HomeDetailViewController.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
#import "SendMsgViewController.h"
#import "UMSocial.h"

@interface HomeDetailViewController ()<UMSocialUIDelegate>{
    NSDictionary *_goodsDic;
    NSMutableArray *_photosList;
    UIButton *_rightBtn;
}

@end

@implementation HomeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navLabel.text = @"货源详情";
    _photosList = [[NSMutableArray alloc] initWithCapacity:10];
    [self getGoodsDetail];
    [_remarkBGImg setImage:[[UIImage imageNamed:@"remark.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8,8,8,8)]];
    [_scrollView setContentSize:CGSizeMake(self.view.frame.size.width, 740)];
    
    if (_isModify){
        UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(320 - 70, self.navView.frame.size.height-38, 60, 30)];
        [rightBtn setTitle:@"修改" forState:UIControlStateNormal];
        [rightBtn setBackgroundImage:[UIImage imageNamed:@"back_n.png"] forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(gotoModifyView) forControlEvents:UIControlEventTouchUpInside];
        [self.navView addSubview:rightBtn];
        [_delBtn setHidden:NO];
    }else{
        [_delBtn setHidden:YES];
    }
   
    
    // Do any additional setup after loading the view from its nib.
}

- (void)gotoModifyView{
    SendMsgViewController *vc = [[SendMsgViewController alloc] initWithNibName:nil bundle:nil];
    vc.goodsDic = _goodsDic;
    [(BasicViewController *)vc setNavStr:@"货源发布"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -删除
- (IBAction)deleteOrder:(id)sender{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"goods_id":_goodsId}];
    
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@pro/del",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  NSLog(@"responseObject=%@",responseObject);
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDataGoodsList" object:nil];
                                  [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                  [self backBtnAct:nil];
                              }];
}


#pragma mark -货源预定
- (void)getReservationsOrder{
    if ([[[GlobalData sharedGlobalData] userinfoDic][@"UserName"]integerValue] == [_goodsDic[@"UserName"] integerValue]&&_isHiddenBook == NO&&[[GlobalData sharedGlobalData] userinfoDic]!=nil) {
        NSString *content = [NSString stringWithFormat:@"新货源 %@  %@   %@  %@  %@  %@ 来自【物流百事通】下载地址：（  http://www.zhi56.cn/home/ld  ）",_nameLabel.text,_startingLabel.text,_destinationLabel.text,_weightLabel.text,_volumeLabel.text,_telLabel.text];
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:UMENG_APPKEY
                                          shareText:content
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToTencent,UMShareToEmail,UMShareToSms,nil]
                                           delegate:self];
        return;
    }

    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"Userid":[[GlobalData sharedGlobalData] userinfoDic][@"UserID"],@"Goods_id":_goodsId}];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@order/new",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  NSLog(@"responseObject=%@",responseObject);
                                  switch ([responseObject[@"result"] integerValue]) {
                                      case 0:
                                          [SVProgressHUD showSuccessWithStatus:@"预定失效"];
                                          break;
                                      case 1:
                                          [SVProgressHUD showSuccessWithStatus:@"预定成功"];
                                          break;
                                      case -1:
                                          [SVProgressHUD showSuccessWithStatus:@"已预订"];
                                          break;
                                          
                                      default:
                                          [SVProgressHUD showSuccessWithStatus:@"预定失败"];
                                          break;
                                  }

                              }];
   
}

- (void)getGoodsDetail{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"goods_id":_goodsId}];
    
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@pro/info",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  _goodsDic = responseObject;
                                  [self configUI];
                                  
                              }];
}

- (void)configUI{
    if ([[[GlobalData sharedGlobalData] userinfoDic][@"UserID"] intValue] == [_goodsDic[@"UserID"] intValue]) {
        [_delBtn setHidden:NO];
    }else{
        [_delBtn setHidden:YES];
    }
    if ([[GlobalData sharedGlobalData] userinfoDic] != nil &&_isHiddenBook == NO) {
        if ([[[GlobalData sharedGlobalData] userinfoDic][@"UserName"]integerValue] == [_goodsDic[@"UserName"] integerValue]){
            _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 70, self.navView.frame.size.height-38, 60, 30)];
            [_rightBtn setTitle:@"分享" forState:UIControlStateNormal];
            [_rightBtn setBackgroundImage:[UIImage imageNamed:@"back_n.png"] forState:UIControlStateNormal];
            [_rightBtn addTarget:self action:@selector(getReservationsOrder) forControlEvents:UIControlEventTouchUpInside];
            [self.navView addSubview:_rightBtn];
            
        }else{
            
            _rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 70, self.navView.frame.size.height-38, 60, 30)];
            [_rightBtn setTitle:@"预定" forState:UIControlStateNormal];
            [_rightBtn setBackgroundImage:[UIImage imageNamed:@"back_n.png"] forState:UIControlStateNormal];
            [_rightBtn addTarget:self action:@selector(getReservationsOrder) forControlEvents:UIControlEventTouchUpInside];
            [self.navView addSubview:_rightBtn];
        }
    }
    _nameLabel.text = _goodsDic[@"GoodsName"];
    _timeLabel.text = _goodsDic[@"UpdateTime"];
    _viewNumLabel.text = [NSString stringWithFormat:@"浏览次数：%@",_goodsDic[@"ViewNum"]];
    if (_goodsDic[@"StartingName"] != [NSNull null]) {
        NSArray *startinglist = [_goodsDic[@"StartingName"] componentsSeparatedByString:@"——"];
        _startingLabel.text = [startinglist lastObject];
    }
    if (_goodsDic[@"DestinationName"] !=[NSNull null]) {
        NSArray *destination = [_goodsDic[@"DestinationName"] componentsSeparatedByString:@"——"];
        _destinationLabel.text = [destination lastObject];
    }
    if (_goodsDic[@"GoodsWeight"] !=[NSNull null]) {
        _weightLabel.text = [NSString stringWithFormat:@"%@吨",_goodsDic[@"GoodsWeight"]];
    }
    if (_goodsDic[@"GoodsVolume"] !=[NSNull null]) {
        _volumeLabel.text = [NSString stringWithFormat:@"%@立方",_goodsDic[@"GoodsVolume"]];
    }
    if (_goodsDic[@"DeliverTime"] !=[NSNull null]) {
        _dateLabel.text = _goodsDic[@"DeliverTime"];
    }
    if (_goodsDic[@"Remark"] !=[NSNull null]) {
        _remarkTextView.text = _goodsDic[@"Remark"];
    }
    if (_goodsDic[@"CarSpecName"] !=[NSNull null]) {
        _specLabel.text = _goodsDic[@"CarSpecName"];
    }
    if (_goodsDic[@"CarTypeName"] !=[NSNull null]) {
        _typeLabel.text = _goodsDic[@"CarTypeName"];
    }
    if (_goodsDic[@"TrueName"] !=[NSNull null]) {
        _sendNameLabel.text = _goodsDic[@"TrueName"];
    }
    if (_goodsDic[@"UserName"] !=[NSNull null]) {
        _telLabel.text = _goodsDic[@"UserName"];
    }
    

//    if ([_goodsDic[@"Affix"] count] >0) {
//        [self paretoImgs];
//    }
    
    NSMutableArray *focusData = [[NSMutableArray alloc] initWithCapacity:10];
    for (int i=0; i<[_goodsDic[@"Affix"] count]; i++) {
        NSString *path = [_goodsDic[@"Affix"][i][@"FileName"] stringByReplacingOccurrencesOfString:@"~" withString:@""];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",URL_ROOT_PIC,path];
        [focusData addObject:[NSDictionary dictionaryWithObjectsAndKeys:imgUrl,@"image",
                              @"pic1",@"title",
                              @NO,@"isLocal",nil]];
    }
    [_focusView configUIWithFocusdata:focusData hasTitle:NO animateInterval:3];
}

- (IBAction)callPhone:(id)sender{
    [[GlobalData sharedGlobalData] phoneBtnActWithNum:_telLabel.text];
    if (_telLabel.text.length == 0) {
        return;
    }
    //传入的参数
    NSString *user_name = [[GlobalData sharedGlobalData] userinfoDic][@"UserName"];
    if (!user_name) {
        user_name = @"";
    }
    NSString *url = [NSString stringWithFormat:@"%@user/boda?api_key=%@&user_name=%@&to_username=%@",URL_ROOT,[[@"1234567890!@#" md5HexDigest] uppercaseString],user_name,_telLabel.text];
    [[BaseNetwork alloc] initWithMethodUrl:url
                                    params:nil
                               requestMode:DGHTTPMethodGET
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  id responseObject = result;
                                  [SVProgressHUD dismiss];
                                  _goodsDic = responseObject;
                                  [self configUI];
                                  
                              }];
    
}

- (void)paretoImgs{
    //拍照
    float width = 60;
    float height = 60;
    float origX = 0;
    float origY = (_ImgsScroll.frame.size.height-height)/2.0;
    float gapX = 13;
    for (int i=0; i<[_goodsDic[@"Affix"] count]; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(origX+(gapX+width)*i, origY, width, height)];

        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 3.0;
        NSString *path = [_goodsDic[@"Affix"][i][@"FileName"] stringByReplacingOccurrencesOfString:@"~" withString:@""];
        NSString *url = [NSString stringWithFormat:@"%@%@",URL_ROOT_PIC,path];
        // 下载图片
        [imageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:nil];
        // 事件监听
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)]];
        // 内容模式
        imageView.clipsToBounds = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [_ImgsScroll addSubview:imageView];
        [_photosList addObject:imageView];
    }
    _ImgsScroll.contentSize = CGSizeMake([_goodsDic[@"Affix"] count] >= 4 ? origX+(gapX+width)*[_goodsDic[@"Affix"] count]:origX+(gapX+width)*[_goodsDic[@"Affix"] count]+45, _ImgsScroll.frame.size.height);
}

- (void)tapImage:(UITapGestureRecognizer *)tap {
    int count = [_goodsDic[@"Affix"] count];
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        // 替换为中等尺寸图片
        NSString *path = [_goodsDic[@"Affix"][i][@"FileName"] stringByReplacingOccurrencesOfString:@"~" withString:@""];
        NSString *url = [NSString stringWithFormat:@"%@%@",URL_ROOT_PIC,path];
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.srcImageView = [_photosList objectAtIndex:i];
        photo.url = [NSURL URLWithString:url]; // 图片路径
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = (tap.view.tag>=100)?(tap.view.tag-100):tap.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
